const {
  getVoteList,
  putVote,
  getVoteInfo,
  insetVoterRecord,
  insetVoteRecord,
  checkVote
} = require('../controller/vote') // controller 逻辑
const { SuccessModel, ErrorModel } = require('../model/resModel') // 返回json状态
const { checkLogin } = require('../utils') // 工具方法

module.exports = async (req, res) => {
  // post 投票列表
  if (req.method === 'POST' && req.path === '/api/Candidate/lst') {
    // 检查登录状态
    const isLogin = checkLogin(req.session.account)
    if (isLogin) return isLogin
    // 获取数据类型
    let { sign } = req.body
    // 检查是否已投票
    const isVote = await checkVote(req.session.account)
    if (isVote.find(d => d.status === sign)) return new ErrorModel('已经投过票了，不能重复投票了～')
    // 查询数据
    try {
      let result = await getVoteList(sign)
      return new SuccessModel(result, '获取成功')
    } catch(e) {
      return new ErrorModel('数据库错误')
    }
  }

  // post 投票
  if (req.method === 'POST' && req.path === '/api/vote/put_vote') {
    // 检查登录状态
    const isLogin = checkLogin(req.session.account)
    if (isLogin) return isLogin
    // 定义数据
    let params = { account: req.session.account, sign: req.body.sign }
    // 检查是否已投票
    const isVote = await checkVote(req.session.account)
    if (isVote.find(d => d.status === params.sign)) return new ErrorModel('已经投过票了，不能重复投票了～')
    // 投票
    try {
      let result = await insetVoterRecord(params)
      if (result.isVote) {
        return new ErrorModel('已投过票，请勿重复投票')
      } else {
        await putVote(req.body)
        await insetVoteRecord(req.body, params.account)
        return new SuccessModel('投票成功')
      }
    } catch(e) {
      return new ErrorModel('数据库错误')
    }
  }

  // post 投票进度查询
  if (req.method === 'POST' && req.path === '/api/Look/schedule') {
    let { sign } = req.body
    try {
      let result = await getVoteInfo(sign)
      return new SuccessModel(result, '获取成功')
    } catch(e) {
      return new ErrorModel('数据库错误')
    }
  }
  
  //get 投票测试接口
  // if (req.method === 'GET' && req.path === '/api/vote/put_vote') {
  //   const params = {"ids":[{"id":1,"name":"张三"},{"id":2,"name":"李四"}],"sign":"personal"}
  //   let result1 = await getTestVote(1, 'personal')
  //   await putVote(params)
  //   let result2 = await getTestVote(1, 'personal')
  //   console.log(`之前的票数${result1[0].personal}---现在的票数${result2[0].personal}`)
  // }
}
